package com.zhengke.controller;

import com.zhengke.common.object.AjaxDone;
import com.zhengke.common.util.*;
import com.zhengke.pojo.ReturnAjax;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhengke.common.object.Result;
import com.zhengke.pojo.Typgl;
import com.zhengke.service.TypglService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import sun.security.krb5.internal.crypto.RsaMd5CksumType;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
//@RequestMapping("")
public class TypglController {

    @Autowired
    private TypglService service;


    @RequestMapping("goods!queryGoods")//用作跳转，到供应商信息页面
    public String query() {
        return "typgl/list";
    }


    /**
     * 信息查询
     */
    @RequestMapping("typgl/list")
    @ResponseBody
    public Result list(String goods_name, String supplier_name, String area_name, int page, int limit, ModelMap model) {
        Result rs = null;
        try {
            rs = service.queryTypgls(goods_name, supplier_name, area_name, page, limit);
            return rs;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result();
    }


    @RequestMapping("Typgl/updates.do")//用作跳转，到修改信息页面
    public String update() {
        return "typgl/toGcUpd2";
    }

    /**
     * 修改信息
     */
    @RequestMapping("Typgl/updatess.do")
    @ResponseBody
    public Result uptatesSuppliers(Typgl typgl) {
        Result rs = null;
        try {
            rs = service.updateTypgls(typgl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 到修改图片页面
     *
     * @return
     */
    @RequestMapping("Typgl/toPicsPage.do")
    public String updatePics(HttpServletRequest request, ModelMap model) {
        String goodsId = request.getParameter("goodsId");
        model.put("goodsId",goodsId);
        String fileServerUrl = null;
        List<Typgl> typgls = null;

        try {
            fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
            typgls = service.queryPics(goodsId);
        } catch (Exception e) {
            e.printStackTrace();
        }


        for (Typgl typgl : typgls) {

            String infoPicPath = typgl.getInfo_picPath();
            String thumbPicPath = typgl.getThumb_picPath();
            String picPath1 = typgl.getPicPath1();
            String picPath2 = typgl.getPicPath2();
            String picPath3 = typgl.getPicPath3();
            String picPath4 = typgl.getPicPath4();
            String picPath5 = typgl.getPicPath5();
            if (!"".equals(picPath1) && picPath1 != null) {
                picPath1 = fileServerUrl + typgl.getPicPath1();
            }
            if (!"".equals(picPath2) && picPath2 != null) {
                picPath2 = fileServerUrl + typgl.getPicPath2();
            }
            if (!"".equals(picPath3) && picPath3 != null) {
                picPath3 = fileServerUrl + typgl.getPicPath3();
            }
            if (!"".equals(picPath4) && picPath4 != null) {
                picPath4 = fileServerUrl + typgl.getPicPath4();
            }
            if (!"".equals(picPath5) && picPath5 != null) {
                picPath5 = fileServerUrl + typgl.getPicPath5();
            }
            if (!"".equals(thumbPicPath) && thumbPicPath != null) {
                thumbPicPath = fileServerUrl + typgl.getThumb_picPath();
            }
            if (!"".equals(infoPicPath) && infoPicPath != null) {
                infoPicPath = fileServerUrl + typgl.getInfo_picPath();
            }

            model.put("picPath1", picPath1);
            model.put("picPath2", picPath2);
            model.put("picPath3", picPath3);
            model.put("picPath4", picPath4);
            model.put("picPath5", picPath5);
            model.put("infoPicPath", infoPicPath);
            model.put("thumbPicPath", thumbPicPath);
        }

        return "typgl/toUpdatePics";
    }

    /**
     * 跳转到轮播图编辑页面
     *
     * @return
     */
    @RequestMapping("Typgl/toEditLunboPage")
    public String toEditLunboPage() {

        return "typgl/editLunboPic";
    }


    /**
     * 跳转到编辑图片页面(单张图片)
     *
     * @param request
     * @param map
     * @return
     */
    @RequestMapping("Typgl/toEditPicsPage.do")
    public String toEditPicsPage(HttpServletRequest request, ModelMap map) {
        String picPath = request.getParameter("picPath");
        String goodsId = request.getParameter("goodsId");

        map.put("picPath", picPath);
        map.put("goodsId", goodsId);
        return "typgl/editPicPage";
    }


    /**
     * 上传图片(单张)
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("Typgl/uploadPictures.do")
    public Object UploadPictures(@RequestParam CommonsMultipartFile file) {
        try {
            String imageFileName = file.getOriginalFilename();
            String extName = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);
            if (file != null && !file.isEmpty()) {
                String path = LoadProperties.findValue("imgPath") + "/" + DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss") + "." + extName;
                File file1 = new File(path);
                if (!file1.getParentFile().exists()) {
                    file1.getParentFile().mkdirs();
                }
                FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
                //上传fastDFS后图片完整地址
                String file_id = FastDfsApiOpr.upload(file1.getPath(), extName);
                //读取config.properties查找访问路径的ip+端口
                String rtnPath = LoadProperties.findValue("FILE_SERVER_URL") + file_id;
                //String rtnPath = LoadProperties.findValue("viewUrl")+"?path="+file1.getPath();
                if (file1 != null) {
                    file1.delete();
                }
                Map<String, Object> data = new HashMap<String, Object>();
                data.put("src", rtnPath);
                ReturnAjax ra = new ReturnAjax();
                ra.setData(data);
                ra.setMsg("成功");
                ra.setCode("0");
                return ra;
            } else {
                return new ReturnAjax("300", "文件格式不正确，请上传 *.png,*.jpeg,*.gif,*.jpg类型图片");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnAjax("300", "上传失败");
    }


    /**
     * 上传多个文件(依次请求)
     *
     * @param file
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("Typgl/uploadLunboPics.do")
    public ReturnAjax uploadFiles(@RequestParam CommonsMultipartFile file, @RequestParam String goodsId) throws Exception {
        ReturnAjax ra = new ReturnAjax();

        String imageFileName = file.getOriginalFilename();
        String extName = imageFileName.substring(imageFileName.lastIndexOf(".") + 1);

        if (file != null && !file.isEmpty()) {
            String path = LoadProperties.findValue("imgPath") + "/" + DateUtil.getSystemDateTimeByFormat("yyyyMMddHHmmss") + "." + extName;
            File file1 = new File(path);
            if (!file1.getParentFile().exists()) {
                file1.getParentFile().mkdirs();
            }
            FileUtils.copyInputStreamToFile(file.getInputStream(), file1);
            //上传fastDFS后图片完整地址
            String file_id = FastDfsApiOpr.upload(file1.getPath(), extName);
            //读取config.properties查找访问路径的ip+端口
            String rtnPath = LoadProperties.findValue("FILE_SERVER_URL") + file_id;
            //String rtnPath = LoadProperties.findValue("viewUrl")+"?path="+file1.getPath();
            if (file1 != null) {
                file1.delete();
            }

            List<Typgl> typgls = service.queryPics(goodsId);
            int i = 0;
            if (null != file_id && !file_id.isEmpty()) {
                for (Typgl typgl : typgls) {
                    String picPath1 = LoadProperties.findValue("FILE_SERVER_URL") +typgl.getPicPath1();
                    if (FastDFSUtils.isExist(picPath1)){
                        FastDfsApiOpr.deleteFile(typgl.getPicPath1());
                    }
                    typgl.setPicPath1(typgl.getPicPath2());
                    typgl.setPicPath2(typgl.getPicPath3());
                    typgl.setPicPath3(typgl.getPicPath4());
                    typgl.setPicPath4(typgl.getPicPath5());
                    typgl.setPicPath5(file_id);
                    typgl.setGoods_id(typgl.getGoods_id());
                    i = service.updatePic(typgl);
                }
            }
            if (i > 0) {
                Map<String, Object> data = new HashMap<>();
                data.put("data", rtnPath);
                ra.setCode("200");
                ra.setMsg("上传成功");
                ra.setData(data);
                return ra;
            }
        }
        return new ReturnAjax("300", "上传失败", null);
    }


    /**
     * 保存图片修改(单张)
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("Typgl/updatePic.do")
    public AjaxDone updatePic(HttpServletRequest request) {

        String goodsId = request.getParameter("goodsId");
        String picpath1 = request.getParameter("picpath1");
        String picpath2 = request.getParameter("picpath2");
        String mark = request.getParameter("mark");
        try {
            String fileServerUrl = LoadProperties.findValue("FILE_SERVER_URL");
            Typgl typgl = new Typgl();
            if (!"".equals(goodsId) && goodsId != null) {
                typgl.setGoods_id(Integer.parseInt(goodsId));
            }

            if (!"".equals(mark) && mark != null && "thumbPic".equals(mark)) {
                if (!"".equals(picpath2) && picpath2 != null) {
                    typgl.setThumb_picPath(picpath2.replace(fileServerUrl, ""));
                }

            } else if (!"".equals(mark) && mark != null && "infoPic".equals(mark)) {
                if (!"".equals(picpath2) && picpath2 != null) {
                    typgl.setInfo_picPath(picpath2.replace(fileServerUrl, ""));
                }
            }
            int i = service.updatePic(typgl);
            if (i > 0) {
                Boolean exist = FastDFSUtils.isExist(picpath1);
                if (exist && !picpath1.equals(picpath2)) {
                    FastDfsApiOpr.deleteFile(picpath1.replace(fileServerUrl,""));
                }
            }
            return new AjaxDone("200", "上传成功!");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统异常!");
    }
}
